// 通用函数
import useClipboard from 'vue-clipboard3';
import { ElMessage } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { useI18n } from 'vue-i18n';
import request from '/@/utils/request';
import axios from 'axios';
import { Session } from '/@/utils/storage';
import { useRouter } from 'vue-router';

export default function () {
	const { t } = useI18n();
	const { toClipboard } = useClipboard();

	// 百分比格式化
	const percentFormat = (row: EmptyArrayType, column: number, cellValue: string) => {
		return cellValue ? `${cellValue}%` : '-';
	};
	// 列表日期时间格式化
	const dateFormatYMD = (row: EmptyArrayType, column: number, cellValue: string) => {
		if (!cellValue) return '-';
		return formatDate(new Date(cellValue), 'YYYY-mm-dd');
	};
	// 列表日期时间格式化
	const dateFormatYMDHMS = (row: EmptyArrayType, column: number, cellValue: string) => {
		if (!cellValue) return '-';
		return formatDate(new Date(cellValue), 'YYYY-mm-dd HH:MM:SS');
	};
	// 列表日期时间格式化
	const dateFormatHMS = (row: EmptyArrayType, column: number, cellValue: string) => {
		if (!cellValue) return '-';
		let time = 0;
		if (typeof row === 'number') time = row;
		if (typeof cellValue === 'number') time = cellValue;
		return formatDate(new Date(time * 1000), 'HH:MM:SS');
	};
	// 小数格式化
	const scaleFormat = (value: string = '0', scale: number = 4) => {
		return Number.parseFloat(value).toFixed(scale);
	};
	// 小数格式化
	const scale2Format = (value: string = '0') => {
		return Number.parseFloat(value).toFixed(2);
	};
	// 点击复制文本
	const copyText = (text: string) => {
		return new Promise((resolve, reject) => {
			try {
				//复制
				toClipboard(text);
				//下面可以设置复制成功的提示框等操作
				ElMessage.success(t('message.layout.copyTextSuccess'));
				resolve(text);
			} catch (e) {
				//复制失败
				ElMessage.error(t('message.layout.copyTextError'));
				reject(e);
			}
		});
	};
	/**
	 * 匹配文字变色（搜索时）
	 * @param val 当前值字符串
	 * @param text 要处理的字符串值
	 * @param color 搜索到时字体高亮颜色
	 * @returns 返回处理后的字符串
	 */
	const markTextColor = (val: string, text = '', color = 'red') => {
		// 返回内容，添加颜色
		let v = text.replace(new RegExp(val, 'gi'), `<font style='color: ${color}'>${val}</font>`);
		// 返回结果
		return v;
	}

	/**
	 * 获取监控阈值
	 * @param key 
	 * @returns 
	 */
	const getThreshold =  (key: string) => {
		return request.get(`system/threshold/${key}`);
	}

	// 导出文件
	const exportFile = (param: any) => {
		const instance = axios.create({
			baseURL: import.meta.env.VITE_API_URL, // url = base url + request url
			withCredentials: true, // send cookies when cross-domain requests
			// timeout: 5000, // request timeout
			responseType: 'blob',
			headers: {
			'Content-type': 'application/json',
			token: `${Session.get('token')}`
			}
		});
	
		instance({
			method: 'get',
			url: param.url, 
			params: {
				...param.params,
			}
		}).then((res: any) => {
			const content = res.data;
			const blob = new Blob([content]); //构造一个blob对象来处理数据
			//对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
			//IE10以上支持blob但是依然不支持download
			if ('download' in document.createElement('a')) {
				//支持a标签download的浏览器
				const link = document.createElement('a'); //创建a标签
				link.download = param.fileName; //a标签添加属性
				link.style.display = 'none';
				link.href = URL.createObjectURL(blob);
				document.body.appendChild(link);
				link.click(); //执行下载
				URL.revokeObjectURL(link.href); //释放url
				document.body.removeChild(link); //释放标签
			} else {
				//其他浏览器
				navigator.msSaveBlob(blob, param.fileName);
			}
		}).catch(err => {
		});
	}

	// 打印文件
	const printFile = (param: any) => {
		const instance = axios.create({
			baseURL: import.meta.env.VITE_API_URL, // url = base url + request url
			withCredentials: true, // send cookies when cross-domain requests
			// timeout: 5000, // request timeout
			responseType: 'blob',
			headers: {
			'Content-type': 'application/json',
			token: `${Session.get('token')}`
			}
		});

		instance({
			method: 'get',
			url: param.url, 
		}).then(res => {
			const content = res.data;
			const blob = new Blob([content],{type: 'application/pdf;charset=utf-8'})
			let url = window.URL.createObjectURL(blob);
			window.open(url);
		}).catch(err => {
		});
	}

	// 下载文件
	const downloadFile = (param: any) => {
		const instance = axios.create({
			baseURL: import.meta.env.VITE_API_URL as any, // url = base url + request url
			withCredentials: true, // send cookies when cross-domain requests
			// timeout: 5000, // request timeout
			responseType: 'blob',
			headers: {
				'Content-type': 'application/json',
				token: `${Session.get('token')}`
			}
		});

		instance({
			method: 'get',
			url: `/file/download/${param.id}`
		}).then(res => {
			const content = res.data;
			const blob = new Blob([content]); //构造一个blob对象来处理数据
			const fileName = param.wbwjm + '.' + param.hzm;
			//对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
			//IE10以上支持blob但是依然不支持download
			if ('download' in document.createElement('a')) {
				//支持a标签download的浏览器
				const link = document.createElement('a'); //创建a标签
				link.download = fileName; //a标签添加属性
				link.style.display = 'none';
				link.href = URL.createObjectURL(blob);
				document.body.appendChild(link);
				link.click(); //执行下载
				URL.revokeObjectURL(link.href); //释放url
				document.body.removeChild(link); //释放标签
			} else {
				//其他浏览器
				navigator.msSaveBlob(blob, fileName);
			}
		})
		.catch(err => {
		});
	}

	// 预览文件
	const router = useRouter()
	const viewFile = (attachment: any, disableDownload ?: number) => {
		let viewType = '';
		disableDownload = disableDownload || 0;
		if (attachment.hzm == 'PNG' || attachment.hzm == 'JPG' || attachment.hzm == 'BMP') {
			viewType="IMAGE"
		} else if (attachment.hzm == 'PDF') {
			viewType="PDF"
		} else if(attachment.hzm == "MP4"){
			viewType="VIDEO"
		} else if(attachment.hzm == "MP3"){
			viewType="AUDIO"
		}
		if(viewType !== ""){
			const {href} = router.resolve({
			name:"fileView",
			params: {
				id: attachment.id,
				type: viewType,
				disableDownload: disableDownload
			}
			})
			window.open(href, '_blank');
		}else{
			if (disableDownload === 1) {
				ElMessage.error("无权下载/No permission to download.");
			} else {
				downloadFile(attachment);
			}
		}
	}

	// 获取状态描述
	const getStatusDesc = (status: 10 | 20 | 88 | 89 | 98 | 99, customizeStatusMap?: any) => {
		let statusMap = {
			10 : {zh: '草稿', en: 'Draft'},
			20 : {zh: '提交', en: 'Submit'},
			88 : {zh: '审批中', en: 'Processing'},
			89 : {zh: '已审批', en: 'Processed'},
			98 : {zh: '作废', en: 'Invalid'},
			99 : {zh: '关闭', en: 'Closed'},
		};
		if (statusMap) {
			statusMap = {
				...statusMap,
				...customizeStatusMap,
			}
		}
		const statusObj = statusMap[status] || {};
		return statusObj.zh + ' ' + statusObj.en;
	}

	return {
		percentFormat,
		dateFormatYMD,
		dateFormatYMDHMS,
		dateFormatHMS,
		scaleFormat,
		scale2Format,
		copyText,
		markTextColor,
		getThreshold,
		exportFile,
		printFile,
		downloadFile,
		getStatusDesc,
		viewFile,
	};
}
